package luj.tool.jnproxyan.proxy.network.socks.actor.root.message.http.client2p.request.add;

import luj.tool.jnproxyan.framework.proxy.actor.tell.ActorTeller;
import luj.tool.jnproxyan.proxy.network.socks.actor.root.Socks5Actor;
import luj.tool.jnproxyan.proxy.network.socks.actor.root.message.http.client2p.request.flush.HttpReqFlushMsg;
import luj.tool.jnproxyan.proxy.network.socks.request.RequestBody;
import luj.tool.jnproxyan.proxy.network.socks.request.SocksRequest;
import luj.tool.jnproxyan.proxy.network.socks.request.op.SocksReqGetter;
import luj.tool.jnproxyan.proxy.stats.http.history.HttpHistoryAdder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
final class OnC2pHttpReq implements Socks5Actor.Handler<C2pHttpRequestMsg> {

  /**
   * @see luj.tool.jnproxyan.proxy.network.socks.actor.root.message.http.client2p.request.flush.OnHttpReqFlush#onHandle
   */
  @Override
  public void onHandle(Context ctx) throws Exception {
    Socks5Actor self = ctx.getActorState(this);
    C2pHttpRequestMsg msg = ctx.getMessage(this);

    Long socksId = msg.socksId();
    SocksRequest req = _reqGetter.inject(self, socksId).getReq();
    req.getWebReqQueue().addLast(msg.data());

    RequestBody socksBody = req.getBody();
    new HttpHistoryAdder(self.getHttpHistoryDat(), socksId, socksBody, msg.requestTime()).add();

    Ref selfRef = ctx.getActorRef();
    _actorTeller.inject(selfRef).tell(HttpReqFlushMsg.class, (b, m) -> b
        .f(m::reqId).set(socksId)
    );
  }

  @Autowired
  SocksReqGetter _reqGetter;

  @Autowired
  ActorTeller _actorTeller;
}
